<template>
  <div class="code-standard p-4">
    <!-- 顶部横幅 -->
    <div class="overview-banner mb-6 bg-gradient-to-r from-blue-500 to-blue-700 text-white rounded-lg shadow-lg p-6">
      <div class="flex justify-between items-center">
        <div>
          <h1 class="text-2xl font-bold mb-2">代码标准管理</h1>
          <p class="opacity-80">管理、维护统一的数据标准代码，确保数据一致性和准确性</p>
        </div>
        <div class="flex space-x-4">
          <el-button type="primary" plain @click="handleAdd">
            <div class="i-carbon-add mr-1"></div>新增
          </el-button>
          <el-button type="danger" plain @click="handleBatchDelete" :disabled="!selectedRows.length">
            <div class="i-carbon-trash-can mr-1"></div>删除
          </el-button>
        </div>
      </div>
    </div>

    <div class="flex gap-4">
      <!-- 左侧分类树 -->
      <div class="w-1/4 bg-white rounded-lg shadow-md p-4">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-lg font-bold">代码分类</h2>
          <div class="flex space-x-2">
            <el-button type="primary" size="small" @click="handleAddCategory">
              <div class="i-carbon-add"></div>
            </el-button>
            <el-button type="primary" size="small" @click="handleEditCategory" :disabled="!currentCategory">
              <div class="i-carbon-edit"></div>
            </el-button>
            <el-button type="danger" size="small" @click="handleDeleteCategory" :disabled="!currentCategory">
              <div class="i-carbon-trash-can"></div>
            </el-button>
          </div>
        </div>
        
        <div class="mb-4">
          <el-input
            v-model="categoryKeyword"
            placeholder="请输入关键字"
            prefix-icon="Search"
            clearable
          />
        </div>
        
        <div class="category-tree h-[calc(100vh-330px)] overflow-auto">
          <el-tree
            ref="categoryTree"
            :data="categoryData"
            :props="defaultProps"
            highlight-current
            node-key="id"
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
            default-expand-all
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span class="flex items-center">
                  <span v-if="data.isLeaf" class="i-carbon-tag-group text-blue-500 mr-2"></span>
                  <span v-else class="i-carbon-folder text-yellow-500 mr-2"></span>
                  <span>{{ node.label }}</span>
                </span>
                <span class="text-xs text-gray-500" v-if="data.code">[{{ data.code }}]</span>
              </span>
            </template>
          </el-tree>
        </div>
      </div>
      
      <!-- 右侧内容 -->
      <div class="w-3/4 space-y-4">
        <!-- 代码标准统计卡片 -->
        <div class="bg-white rounded-lg shadow-md p-4">
          <div class="text-lg font-medium mb-4">{{ currentCategoryName || '全部' }}代码标准(总数)</div>
          <div class="h-64" ref="chartRef"></div>
        </div>
        
        <!-- 代码标准列表 -->
        <div class="bg-white rounded-lg shadow-md p-4">
          <div class="flex justify-between items-center mb-4">
            <div class="flex items-center">
              <span class="text-lg font-bold">代码标准列表</span>
              <el-tag type="info" class="ml-2" v-if="currentCategoryName">{{ currentCategoryName }}</el-tag>
            </div>
            <div class="flex items-center space-x-4">
              <el-input
                v-model="keyword"
                placeholder="请输入关键字"
                prefix-icon="Search"
                clearable
                style="width: 220px"
              />
              <div>
                <el-tabs v-model="activeTab" @tab-change="handleTabChange" class="ml-4">
                  <el-tab-pane name="standard" label="标准数据"></el-tab-pane>
                  <el-tab-pane name="format" label="标准模式"></el-tab-pane>
                  <el-tab-pane name="mapping" label="代码映射关系"></el-tab-pane>
                </el-tabs>
              </div>
            </div>
          </div>
          
          <ArtTable
            :data="filteredTableData"
            :loading="loading"
            :border="true"
            :stripe="true"
            :total="total"
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="80" align="center" />
            <el-table-column prop="name" label="名称" min-width="150" show-overflow-tooltip />
            <el-table-column prop="code" label="编码" width="100" />
            <el-table-column prop="categoryName" label="所属分类" width="120" />
            <el-table-column prop="status" label="是否启用" width="80">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.status"
                  @change="(val) => handleStatusChange(scope.row, val)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="source" label="标准来源" width="100" />
            <el-table-column prop="updateTime" label="最后修改时间" width="160" sortable />
            <el-table-column fixed="right" label="操作" width="220">
              <template #default="scope">
                <el-button
                  size="small"
                  @click="handleEdit(scope.row)"
                >编辑</el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.row)"
                >删除</el-button>
                <el-button
                  size="small"
                  type="success"
                  @click="handleViewMapping(scope.row)"
                  v-if="activeTab === 'standard'"
                >映射</el-button>
              </template>
            </el-table-column>
          </ArtTable>
        </div>
      </div>
    </div>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑代码标准' : '新增代码标准'"
      width="500px"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="类别名称" prop="categoryId">
          <el-cascader
            v-model="form.categoryId"
            :options="categoryOptions"
            :props="{ checkStrictly: true, emitPath: false }"
            placeholder="请选择所属类别"
            clearable
            class="w-full"
          />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-switch v-model="form.status" />
        </el-form-item>
        <el-form-item label="标准来源" prop="source">
          <el-input v-model="form.source" placeholder="请输入标准来源" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 新增/编辑分类对话框 -->
    <el-dialog
      v-model="categoryDialogVisible"
      :title="isEditCategory ? '编辑分类' : '新增分类'"
      width="500px"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="上级分类" v-if="!isEditCategory">
          <el-cascader
            v-model="categoryForm.parentId"
            :options="categoryOptions"
            :props="{ checkStrictly: true, emitPath: false }"
            placeholder="请选择上级分类"
            clearable
            class="w-full"
          />
        </el-form-item>
        <el-form-item label="分类编码" prop="code">
          <el-input v-model="categoryForm.code" placeholder="请输入分类编码" />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCategoryForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watchEffect, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import { RoutesAlias } from '@/router/routesAlias'
import ArtTable from '@/components/core/tables/ArtTable.vue'

const route = useRoute()
const router = useRouter()

// 数据加载和分页
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 关键字搜索
const keyword = ref('')
const categoryKeyword = ref('')

// 分类树相关
const categoryTree = ref(null)
const currentCategory = ref(null)
const currentCategoryId = ref(null)
const currentCategoryName = ref('')

// 选项卡相关
const activeTab = ref('standard')

// 选中行
const selectedRows = ref([])

// 图表引用
const chartRef = ref()
let chart = null

// 分类数据
const categoryData = ref([
  {
    id: 1,
    label: '教职工',
    code: 'JSGZ',
    children: [
      { id: 11, label: '编制类别', code: 'BZLB', isLeaf: true },
      { id: 12, label: '编制异动', code: 'BZYD', isLeaf: true },
      { id: 13, label: '辞职社会聘或学术团队', code: 'CZSHPHTD', isLeaf: true },
      { id: 14, label: '导师类别', code: 'DSLB', isLeaf: true },
      { id: 15, label: '辅导员类型', code: 'FDYLX', isLeaf: true }
    ]
  },
  {
    id: 2,
    label: '科研类',
    code: 'KYL',
    children: [
      { id: 21, label: '科研项目级别', code: 'KYXMJB', isLeaf: true },
      { id: 22, label: '科研成果类型', code: 'KYCGLX', isLeaf: true }
    ]
  },
  {
    id: 3,
    label: '行政类',
    code: 'XZL',
    children: [
      { id: 31, label: '公文类型', code: 'GWLX', isLeaf: true },
      { id: 32, label: '会议类型', code: 'HYLX', isLeaf: true }
    ]
  },
  {
    id: 4,
    label: '学生类',
    code: 'XSL',
    isLeaf: true
  }
])

// 表格数据
const tableData = ref([
  {
    id: 1,
    name: '附设机构类',
    code: 'FSJGL',
    categoryId: 11,
    categoryName: '编制类别',
    status: true,
    source: '1400',
    updateTime: '2021-04-12 10:32:34'
  },
  {
    id: 2,
    name: '科研类',
    code: 'KYL',
    categoryId: 11,
    categoryName: '编制类别',
    status: true,
    source: '1001',
    updateTime: '2020-10-20 16:45:57'
  },
  {
    id: 3,
    name: '行政类',
    code: 'XZL',
    categoryId: 11,
    categoryName: '编制类别',
    status: true,
    source: '1001',
    updateTime: '2020-10-20 16:45:54'
  },
  {
    id: 4,
    name: '教学类',
    code: 'JXL',
    categoryId: 11,
    categoryName: '编制类别',
    status: false,
    source: '1001',
    updateTime: '2020-10-20 16:45:52'
  },
  {
    id: 5,
    name: '数据类',
    code: 'SJL',
    categoryId: 11,
    categoryName: '编制类别',
    status: false,
    source: '1001',
    updateTime: '2019-09-24 15:37:55'
  },
  {
    id: 6,
    name: '工勤类',
    code: 'GQL',
    categoryId: 11,
    categoryName: '编制类别',
    status: false,
    source: '1001',
    updateTime: '2019-09-24 15:37:55'
  },
  {
    id: 7,
    name: '校办企业类',
    code: 'XBQYL',
    categoryId: 11,
    categoryName: '编制类别',
    status: false,
    source: '1001',
    updateTime: '2019-09-24 15:37:55'
  },
  {
    id: 8,
    name: '其他类',
    code: 'QTL',
    categoryId: 11,
    categoryName: '编制类别',
    status: false,
    source: '1001',
    updateTime: '2019-09-24 15:37:55'
  }
])

// 分类选项
const categoryOptions = computed(() => {
  const convert = (data) => {
    return data.map(item => {
      const result = {
        value: item.id,
        label: item.label,
        isLeaf: item.isLeaf
      }
      
      if (item.children && item.children.length > 0) {
        result.children = convert(item.children)
      }
      
      return result
    })
  }
  
  return convert(categoryData.value)
})

// 树配置
const defaultProps = {
  children: 'children',
  label: 'label'
}

// 过滤后的表格数据
const filteredTableData = computed(() => {
  let data = [...tableData.value]
  
  // 根据分类过滤
  if (currentCategoryId.value) {
    data = data.filter(item => item.categoryId === currentCategoryId.value)
  }
  
  // 根据关键字过滤
  if (keyword.value) {
    const kw = keyword.value.toLowerCase()
    data = data.filter(item => 
      item.name.toLowerCase().includes(kw) || 
      item.code.toLowerCase().includes(kw)
    )
  }
  
  total.value = data.length
  return data
})

// 表单相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const form = reactive({
  id: '',
  name: '',
  code: '',
  categoryId: null,
  status: true,
  source: ''
})

const rules = {
  categoryId: [{ required: true, message: '请选择所属类别', trigger: 'change' }],
  code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  source: [{ required: true, message: '请输入标准来源', trigger: 'blur' }]
}

// 分类表单
const categoryDialogVisible = ref(false)
const isEditCategory = ref(false)
const categoryForm = reactive({
  id: '',
  name: '',
  code: '',
  parentId: null
})

const categoryRules = {
  code: [{ required: true, message: '请输入分类编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
}

// 树节点过滤
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.toLowerCase().includes(value.toLowerCase()) || 
         data.code?.toLowerCase().includes(value.toLowerCase())
}

// 监听过滤关键字变化
watchEffect(() => {
  categoryTree.value?.filter(categoryKeyword.value)
})

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  
  chart = echarts.init(chartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 'bottom',
      data: ['教职工', '科研类', '行政类', '数据类', '学生类', '工勤类', '基础类', '业务系统', '公共代码表']
    },
    series: [
      {
        name: '代码标准',
        type: 'pie',
        radius: ['30%', '60%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}\n{c}个'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        data: [
          { value: 30, name: '教职工' },
          { value: 28, name: '科研类' },
          { value: 26, name: '行政类' },
          { value: 19, name: '数据类' },
          { value: 10, name: '学生类' },
          { value: 9, name: '工勤类' },
          { value: 14, name: '基础类' },
          { value: 54, name: '业务系统' },
          { value: 40, name: '公共代码表' }
        ]
      }
    ]
  }
  
  chart.setOption(option)
}

// 窗口大小变化时重新绘制图表
const handleResize = () => {
  chart?.resize()
}

// 处理树节点点击
const handleNodeClick = (data) => {
  currentCategory.value = data
  currentCategoryId.value = data.id
  currentCategoryName.value = data.label
  
  // 如果是叶子节点，显示该分类下的代码标准
  if (data.isLeaf) {
    // 刷新表格数据
    fetchData()
  }
}

// 处理标签页变化
const handleTabChange = () => {
  // 不同标签页可以显示不同数据
  // 这里仅作为示例，实际应该根据标签页请求不同的数据
}

// 新增代码标准
const handleAdd = () => {
  isEdit.value = false
  form.id = ''
  form.name = ''
  form.code = ''
  form.categoryId = currentCategoryId.value || null
  form.status = true
  form.source = ''
  
  dialogVisible.value = true
}

// 编辑代码标准
const handleEdit = (row) => {
  isEdit.value = true
  form.id = row.id
  form.name = row.name
  form.code = row.code
  form.categoryId = row.categoryId
  form.status = row.status
  form.source = row.source
  
  dialogVisible.value = true
}

// 删除代码标准
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除代码标准"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 执行删除逻辑
    tableData.value = tableData.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的${selectedRows.value.length}项数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 执行批量删除逻辑
    const ids = selectedRows.value.map(row => row.id)
    tableData.value = tableData.value.filter(item => !ids.includes(item.id))
    ElMessage.success('批量删除成功')
    selectedRows.value = []
  }).catch(() => {})
}

// 修改状态
const handleStatusChange = (row, status) => {
  ElMessage.success(`${row.name} 状态已${status ? '启用' : '禁用'}`)
}

// 查看映射关系
const handleViewMapping = (row) => {
  router.push({
    path: RoutesAlias.CodeStandardMapping,
    query: {
      id: row.id,
      code: row.code,
      name: row.name
    }
  })
}

// 提交表单
const submitForm = () => {
  const formRef = ref(null)
  
  formRef.value?.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        // 修改
        const index = tableData.value.findIndex(item => item.id === form.id)
        if (index !== -1) {
          const categoryName = findCategoryName(form.categoryId)
          tableData.value[index] = {
            ...form,
            categoryName,
            updateTime: new Date().toLocaleString()
          }
        }
        ElMessage.success('修改成功')
      } else {
        // 新增
        const categoryName = findCategoryName(form.categoryId)
        const newItem = {
          id: tableData.value.length + 1,
          name: form.name,
          code: form.code,
          categoryId: form.categoryId,
          categoryName,
          status: form.status,
          source: form.source,
          updateTime: new Date().toLocaleString()
        }
        tableData.value.unshift(newItem)
        ElMessage.success('新增成功')
      }
      
      dialogVisible.value = false
    }
  })
}

// 根据分类ID查找分类名称
const findCategoryName = (categoryId) => {
  const findNameInTree = (tree) => {
    for (const node of tree) {
      if (node.id === categoryId) {
        return node.label
      }
      if (node.children && node.children.length) {
        const name = findNameInTree(node.children)
        if (name) return name
      }
    }
    return null
  }
  
  return findNameInTree(categoryData.value) || ''
}

// 新增分类
const handleAddCategory = () => {
  isEditCategory.value = false
  categoryForm.id = ''
  categoryForm.name = ''
  categoryForm.code = ''
  categoryForm.parentId = currentCategory.value ? currentCategory.value.id : null
  
  categoryDialogVisible.value = true
}

// 编辑分类
const handleEditCategory = () => {
  if (!currentCategory.value) {
    ElMessage.warning('请先选择一个分类')
    return
  }
  
  isEditCategory.value = true
  categoryForm.id = currentCategory.value.id
  categoryForm.name = currentCategory.value.label
  categoryForm.code = currentCategory.value.code || ''
  
  categoryDialogVisible.value = true
}

// 删除分类
const handleDeleteCategory = () => {
  if (!currentCategory.value) {
    ElMessage.warning('请先选择一个分类')
    return
  }
  
  ElMessageBox.confirm(`确认删除分类"${currentCategory.value.label}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 执行删除逻辑，这里简单处理为从父节点的children中移除
    const removeFromTree = (tree, id) => {
      for (let i = 0; i < tree.length; i++) {
        if (tree[i].id === id) {
          tree.splice(i, 1)
          return true
        }
        if (tree[i].children && tree[i].children.length) {
          if (removeFromTree(tree[i].children, id)) {
            return true
          }
        }
      }
      return false
    }
    
    removeFromTree(categoryData.value, currentCategory.value.id)
    
    currentCategory.value = null
    currentCategoryId.value = null
    currentCategoryName.value = ''
    
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 提交分类表单
const submitCategoryForm = () => {
  const categoryFormRef = ref(null)
  
  categoryFormRef.value?.validate((valid) => {
    if (valid) {
      if (isEditCategory.value) {
        // 修改分类
        const updateInTree = (tree) => {
          for (const node of tree) {
            if (node.id === categoryForm.id) {
              node.label = categoryForm.name
              node.code = categoryForm.code
              return true
            }
            if (node.children && node.children.length) {
              if (updateInTree(node.children)) {
                return true
              }
            }
          }
          return false
        }
        
        updateInTree(categoryData.value)
        ElMessage.success('修改分类成功')
      } else {
        // 新增分类
        const newCategoryId = Date.now()
        const newCategory = {
          id: newCategoryId,
          label: categoryForm.name,
          code: categoryForm.code,
          isLeaf: true
        }
        
        if (categoryForm.parentId) {
          // 添加为子分类
          const addToParent = (tree, parentId) => {
            for (const node of tree) {
              if (node.id === parentId) {
                if (!node.children) {
                  node.children = []
                }
                node.children.push(newCategory)
                node.isLeaf = false
                return true
              }
              if (node.children && node.children.length) {
                if (addToParent(node.children, parentId)) {
                  return true
                }
              }
            }
            return false
          }
          
          addToParent(categoryData.value, categoryForm.parentId)
        } else {
          // 添加为顶级分类
          categoryData.value.push(newCategory)
        }
        
        ElMessage.success('新增分类成功')
      }
      
      categoryDialogVisible.value = false
    }
  })
}

// 分页大小变更
const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchData()
}

// 当前页变更
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchData()
}

// 获取数据
const fetchData = () => {
  loading.value = true
  
  // 模拟请求
  setTimeout(() => {
    loading.value = false
  }, 500)
}

// 初始化
onMounted(() => {
  fetchData()
  initChart()
  window.addEventListener('resize', handleResize)
  
  // 如果有查询参数，直接打开对应的分类
  if (route.query.categoryId) {
    const categoryId = Number(route.query.categoryId)
    // 找到对应分类并选中
    const findAndSelectCategory = (tree) => {
      for (const node of tree) {
        if (node.id === categoryId) {
          categoryTree.value?.setCurrentKey(categoryId)
          handleNodeClick(node)
          return true
        }
        if (node.children && node.children.length) {
          if (findAndSelectCategory(node.children)) {
            return true
          }
        }
      }
      return false
    }
    
    findAndSelectCategory(categoryData.value)
  }
})
</script>

<style scoped lang="scss">
.code-standard {
  .overview-banner {
    position: relative;
    overflow: hidden;
    
    &::before {
      content: '';
      position: absolute;
      top: -50%;
      right: -50%;
      width: 100%;
      height: 200%;
      background-image: linear-gradient(
        45deg,
        rgba(255, 255, 255, 0.1) 25%,
        transparent 25%,
        transparent 50%,
        rgba(255, 255, 255, 0.1) 50%,
        rgba(255, 255, 255, 0.1) 75%,
        transparent 75%,
        transparent
      );
      background-size: 20px 20px;
      transform: rotate(25deg);
      z-index: 1;
    }
  }
  
  .category-tree {
    :deep(.el-tree-node__content) {
      height: 32px;
    }
    
    :deep(.custom-tree-node) {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
    }
  }
}
</style>
